﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Core;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using SkiaSharp;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using VOL.Entity.DomainModels.BasicData;
using VOL.SmartMecial.Dtos;
using VOL.SmartMecial.Infrastructure;
using VOL.SmartMecial.IServices.WorkforceManage;

namespace VOL.SmartMecial.Services.WorkforceManage
{
    public class WardAreaService : IWardAreaService
    {
        /// <summary>
        /// 病区
        /// </summary>
        private readonly IBaseRepository<WardArea> _wardAreaRepository;
        /// <summary>
        /// 病房
        /// </summary>
        private readonly IBaseRepository<WardModel> _wardRepository;
        /// <summary>
        /// 床位
        /// </summary>
        private readonly IBaseRepository<Bed> _bedRepository;
        /// <summary>
        /// 病区病房关联
        /// </summary>
        private readonly IBaseRepository<WardAreaHouseModel> _wardAreaHouseRepository;
        /// <summary>
        /// 患者
        /// </summary>

        private readonly IBaseRepository<Patient> _patientRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="wardAreaRepository">病区</param>
        /// <param name="wardRepository">病房</param>
        /// <param name="bedRepository">床位</param>
        /// <param name="wardAreaHouseRepository">病区病房关联</param>
        public WardAreaService(IBaseRepository<WardArea> wardAreaRepository, IBaseRepository<WardModel> wardRepository, IBaseRepository<Bed> bedRepository, IBaseRepository<WardAreaHouseModel> wardAreaHouseRepository, IBaseRepository<Patient> patientRepository)
        {
            this._wardAreaRepository = wardAreaRepository;
            this._wardRepository = wardRepository;
           this._bedRepository = bedRepository;
            this._wardAreaHouseRepository = wardAreaHouseRepository;
            this._patientRepository = patientRepository;
        }


        /// <summary>
        /// 根据病区id查询病房及床位信息
        /// </summary>
        /// <param name="wardAreaId">病区ID</param>
        /// <returns>病房和床位的树形结构数据</returns>
        public async Task<APIResult<List<WardBedWardAreaDto>>> GetWardAreaBeds(int wardAreaId)
        {
            try
            {
                if (wardAreaId <= 0)
                {
                    return new APIResult<List<WardBedWardAreaDto>>
                    {
                        Code = APIEnum.Error,
                        Msg = "病区ID不能为空或小于等于0",
                        Data = null
                    };
                }

                // 使用联合查询获取病区下的病房数据
                var wardQuery = from wardArea in _wardAreaHouseRepository.GetAll()
                                join ward in _wardRepository.GetAll()
                                on wardArea.WardId equals ward.Id
                                where wardArea.WardAreaId == wardAreaId
                                select new
                                {
                                    WardId = ward.Id,
                                    WardName = ward.WardName
                                };

                // 立即执行查询，避免多次数据库访问
                var wardData = await wardQuery.ToListAsync();

                if (wardData.Count == 0)
                {
                    return new APIResult<List<WardBedWardAreaDto>>
                    {
                        Code = APIEnum.Error,
                        Msg = "未找到该病区下的病房信息",
                        Data = new List<WardBedWardAreaDto>()
                    };
                }

                // 获取相关病房的所有床位 (一次性获取所有相关病房的床位)
                var wardIds = wardData.Select(w => (int?)w.WardId).ToList(); // 转换为可空整型列表
                var beds = await _bedRepository.GetAll()
                    .Where(b => b.WardCode.HasValue && wardIds.Contains(b.WardCode))
                    .ToListAsync();

                // 高效构建返回结果
                var result = new List<WardBedWardAreaDto>(wardData.Count);
                foreach (var ward in wardData)
                {
                    var wardDto = new WardBedWardAreaDto
                    {
                        Value = ward.WardId,
                        Name = ward.WardName,
                        Children = new List<WardBedWardAreaDto>()
                    };

                    // 添加该病房的所有床位
                    foreach (var bed in beds.Where(b => b.WardCode.HasValue && b.WardCode == ward.WardId))
                    {
                        wardDto.Children.Add(new WardBedWardAreaDto
                        {
                            Value = bed.Id,
                            Name = bed.BedCode,
                            Children = new List<WardBedWardAreaDto>() // 床位是叶子节点
                        });
                    }

                    result.Add(wardDto);
                }

                return new APIResult<List<WardBedWardAreaDto>>
                {
                    Code = APIEnum.Success,
                    Msg = "获取成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<List<WardBedWardAreaDto>>
                {
                    Code = APIEnum.Error,
                    Msg = $"获取病区床位信息失败: {ex.Message}",
                    Data = null
                };
            }
        }



        /// <summary>
        /// 病区下拉框
        /// </summary>
        /// <returns>返回</returns>
        public async Task<WebResponseContent> GetWardArea()
        {
            var wardArealist = await _wardAreaRepository.GetAll().ToListAsync();
            var res=new WebResponseContent();
            res.OK("查询成功", wardArealist);
            return res;
        }
        /// <summary>
        /// 分配床位
        /// </summary>
        /// <param name="patientCode"></param>
        /// <param name="bedCode"></param>
        /// <returns></returns>
        public async Task<int> UpdPatient(Patient patient)
        {
            var res = await _patientRepository.UpdateAsync(patient);
            return res;

        }
    }
}
